import { createRouter, createWebHistory } from 'vue-router'
import DefaultLayout from '../components/layout/DefaultLayout.vue'
import { useAuthStore } from '../stores/auth'

const routes = [
  // 登录页，不需要布局和认证
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },

  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '页面未找到' }
  },

  // 所有需要布局和认证的页面
  {
    path: '/',
    component: DefaultLayout,
    meta: { requiresAuth: true }, // 在父路由上设置，所有子路由默认都需要认证
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/Dashboard.vue'),
        meta: { title: '数据一览图' } // 无 sidebar
      },
      {
        path: 'devices',
        redirect: '/devices/list',
        meta: { sidebar: 'device' },
        children: [
          { path: 'list', name: 'DeviceList', component: () => import('../views/device/DeviceList.vue'), meta: { title: '设备管理' } },
          { 
            path: 'discover', // 【新增】设备发现池页面
            name: 'DeviceDiscover', 
            component: () => import('../views/device/DeviceDiscover.vue'), 
            meta: { title: '设备发现' } 
          },
          
          { path: 'detail/:id', name: 'DeviceDetail', component: () => import('../views/device/DeviceDetail.vue'), meta: { title: '设备详情' } },
          {
            path: 'locations',
            name: 'DeviceLocationManagement', // 路由名称建议唯一
            component: () => import('@/views/device/LocationManagement.vue'), // 组件路径保持不变
            meta: { title: '位置管理' }
          },
        ]
      },
      {
        path: 'data-center',
        name: 'DataCenter',
        component: () => import('../views/data-center/DataLog.vue'),
        meta: { title: '数据中心', sidebar: 'datacenter' }
      },
      {
        path: 'visual',
        redirect: '/visual/list',
        meta: { sidebar: 'visual' },
        children: [
          { path: 'list', name: 'VisualList', component: () => import('../views/visual/VisualList.vue'), meta: { title: '视频设备' } },
          { path: 'detail/:id', name: 'VisualDetail', component: () => import('../views/visual/VisualDetail.vue'), meta: { title: '视频查看' } },
          { path: 'alarms', name: 'VisualAlarms', component: () => import('../views/visual/VisualAlarms.vue'), meta: { title: '告警管理' } },
        ]
      },
      {
        path: 'system',
        redirect: '/system/users',
        meta: { sidebar: 'system' },
        children: [
          { path: 'users', name: 'UserManagement', component: () => import('../views/system/UserManagement.vue'), meta: { title: '用户管理' } },
          { path: 'roles', name: 'RoleManagement', component: () => import('../views/system/RoleManagement.vue'), meta: { title: '角色管理' } },
             
        ]
      },
    ]
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0, left: 0 };
    }
  },
});

// --- 合并后的、唯一的全局前置守卫 ---
router.beforeEach((to, from, next) => {
  // 1. 更新页面标题
  const title = to.meta.title || '物联网设备管理平台';
  document.title = `${title} - XXX物联网设备管理平台`;

  // 2. 执行认证逻辑
  const authStore = useAuthStore();
  // 尝试从 localStorage 恢复登录状态。这一步也可以在 App.vue 的 onMounted 中做一次即可。
  authStore.tryAutoLogin(); 
  const isAuthenticated = authStore.isAuthenticated;

  // 判断目标路由是否需要认证
  if (to.meta.requiresAuth) {
    if (isAuthenticated) {
      next(); // 已登录，放行
    } else {
      // 未登录，重定向到登录页
      // 将用户尝试访问的路径作为查询参数，登录后可以跳回去
      next({ name: 'Login', query: { redirect: to.fullPath } });
    }
  } else {
    // 如果访问的是登录页，且用户已登录，则直接跳转到首页
    if (to.name === 'Login' && isAuthenticated) {
      next({ name: 'Dashboard' });
    } else {
      next(); // 不需要认证的页面，直接放行
    }
  }
});

export default router;